$def with (user_info, course, task, submissions, students, eval_submission, user_task, previous_taskid, next_taskid, webterm_link, input_random_list=[])

$#
$# This file is part of INGInious. See the LICENSE and the COPYRIGHTS files for
$# more information about the licensing of this file.
$#

$var title: $:task.get_name(user_manager.session_language()) - $:course.get_name(user_manager.session_language())

$ registered = user_manager.course_is_user_registered(course)
$ staff = user_manager.has_staff_rights_on_course(course)
$ course_tags = course.get_tags()
$ task_categories = task.get_categories()

$# Left column content
$def ColumnF():
    <h3>$:_("Information")</h3>
    <table class="table table-sm">
        $if task.get_authors(user_manager.session_language()):
            <tr>
                <td>$:_("Author(s)")</td>
                <td>$task.get_authors(user_manager.session_language())</td>
            </tr>
        $if task.get_contact_url(user_manager.session_language()):
            <tr>
                <td>$:_("Contact")</td>
                <td><a href="$task.get_contact_url(user_manager.session_language()).format(course_id=course.get_id(), task_id=task.get_id(), username=user_manager.session_username())" target="_blank">$:_("Contact link")</a></td>
            </tr>
        $if not is_lti():
            $if task.get_accessible_time().is_open() and not task.get_accessible_time().is_open_with_soft_deadline():
                <tr class="list-group-item-danger">
                    <td>$:_("Deadline")</td>
                    <td>
                        $task.get_deadline()
                    </td>
                </tr>
            $else:
                <tr>
                    <td>$:_("Deadline")</td>
                    <td>
                        $task.get_deadline()
                    </td>
                </tr>
        $if registered or staff:
            <tr>
                <td>$:_("Status")</td>
                <td id="task_status">
                    $if not eval_submission and len(submissions) == 0:
                        $:_("Not yet attempted")
                    $elif eval_submission is not None and eval_submission["status"] == "done" and eval_submission["result"] == "success":
                        $:_("Succeeded")
                    $else:
                        $ waiting=False
                        $for submission in submissions:
                            $if submission["status"] == "waiting":
                                $ waiting=True
                                $break
                        $if waiting:
                            $:_("Waiting for verification")
                        $else:
                            $:_("Failed")
                </td>
            </tr>
            <tr>
                <td>$:_("Grade")</td>
                <td>
                    <span id="task_grade">$user_task.get('grade', 0)</span>%
                </td>
            </tr>
            $if not is_lti():
                <tr>
                    <td>$:_("Grading weight")</td>
                    <td>$task.get_grading_weight()</td>
                </tr>
            <tr>
                <td>$:_("Attempts")</td>
                <td id="task_tries">
                    $(user_task.get('tried', 0))
                </td>
            </tr>
        <tr>
            <td>$:_("Submission limit")</td>
            <td>
                $ submission_limit = task.get_submission_limit()
                $if submission_limit == {"amount":-1, "period":-1}:
                    $:_("No limitation")
                $else:
                    $if submission_limit["period"] > 0:
                        $:_("{nb_submissions} submissions<br /> every {nb_hours} hour(s)").format(nb_submissions=submission_limit["amount"], nb_hours=submission_limit["period"])
                    $else:
                        $:_("{nb_submissions} submissions").format(nb_submissions=submission_limit["amount"])
            </td>
        </tr>
        $ tags = ""
        $for category in task_categories:
            $ tag = course_tags[category]
            $if tag.is_visible_for_student() or user_manager.has_staff_rights_on_course(course):
                $ tags += (_(tag.get_name(user_manager.session_language())) + ", ")
        $ tags = tags[:-2]
        $if tags != "":
        <tr>
            <td>$:_("Category tags")</td>
            <td>$tags</td>
        </tr>
    </table>
     
    <!-- Tags -->
    $ visible_tags = [course_tags[category] for category in task_categories if course_tags[category].is_visible_for_student() or user_manager.has_staff_rights_on_course(course)]

    $# Auto tags may appear for admins. So we force the h3 title even if there is not predefined tags
    $# We do not show the tag header for students if they can not get tags
    $if len(visible_tags) > 0 :
        <h3>$:_("Tags")</h3>
        <div class="mb-3" id="main_tag_group">
        $for tag in visible_tags:
            $if tag.get_type() == 0:
                <span class="badge alert-info" id="$tag.get_id()" data-placement="right" data-toggle="tooltip" title="$tag.get_description(user_manager.session_language())">$:tag.get_name(user_manager.session_language())</span>
            $elif tag.get_type() == 1:
                <span class="badge alert-danger" id="$tag.get_id()" data-placement="right" data-toggle="tooltip" title="$tag.get_description(user_manager.session_language())" style="display:none;">$:tag.get_name(user_manager.session_language())</span>
        </div>
    <!-- End Tags -->
    
    $if not is_lti() and staff:
        <h3>$:_("Administration")</h3>
        $if not course.is_open_to_non_staff():
            <div class="alert alert-warning" role="alert">
                $:_("This course is currently invisible for students.  You can change this by modifying the \"accessible\" option in the configuration of the course.")
            </div>
        $if not task.get_accessible_time().after_start():
            <div class="alert alert-warning" role="alert">
                $:_("This task is currently invisible for students. You can change this by modifying the \"accessible\" option in the configuration of the task.")
            </div>
        <div class="list-group mb-3">
            <a class="list-group-item list-group-item-action list-group-item-info" href="$get_homepath()/admin/$course.get_id()/submissions?tasks=$task.get_id()">
                <i class="fa fa-tasks fa-fw"></i>&nbsp; $:_("View submissions")
            </a>
            $if user_manager.has_admin_rights_on_course(course):
                <a class="list-group-item list-group-item-action list-group-item-info" href="$get_homepath()/admin/$course.get_id()/edit/task/$task.get_id()">
                    <i class="fa fa-edit fa-fw"></i>&nbsp; $:_("Edit task")
                </a>
                <a href="#" class="list-group-item list-group-item-action list-group-item-info" data-toggle="modal" data-target="#modal-debug">
                    <i class="fa fa-wrench fa-fw"></i>&nbsp; $:_("Debug information")
                </a>
        </div>
    $elif not is_lti() and registered:
        <h3>$:_("Submitting as")</h3>
        <div class="list-group mb-3">
            <div class="list-group-item list-group-item-action list-group-item-info">
                $if task.is_group_task():
                    <i class="fa fa-chevron-right fa-fw"></i>&nbsp; <b>$(_('Group'))</b>
                $else:
                    <i class="fa fa-chevron-right fa-fw"></i>&nbsp; <b>$user_manager.session_realname()</b>
            </div>
            <a class="list-group-item list-group-item-action list-group-item-info" href="$get_homepath()/group/$course.get_id()">
                <i class="fa fa-group fa-fw"></i>&nbsp;
                $ mygroup = user_manager.get_course_user_group(course)
                $if mygroup and user_manager.session_username() in mygroup['students']:
                    $:_("Group : {}").format(mygroup['description'])
                $else:
                    $:_("Groups management")
            </a>
        </div>

    $:template_helper.call('task_menu', course=course, task=task, template_helper=template_helper)
    $if registered:
        <h3>$:_("For evaluation")</h3>
        <div class="list-group mb-3">
            <div class="list-group-item list-group-item-info"><i class="fa fa-info fa-fw"></i>
                $if task.get_evaluate() == "last":
                    $:_("Last submission")
                $elif task.get_evaluate() == "best":
                    $:_("Best submission")
                $else:
                    $:_("Selected submission")
            </div>
            $if eval_submission:
                <a href="#" id="my_submission" class="submission list-group-item list-group-item-action list-group-item-info" data-submission-id="$eval_submission['_id']">
                    <i class="fa fa-chevron-right fa-fw"></i>
                    $eval_submission["submitted_on"].strftime("%d/%m/%Y %H:%M:%S") - $eval_submission.get("grade",0.0)%
                </a>
            $else:
                <div id="my_submission" class="list-group-item list-group-item-info"><i class="fa fa-chevron-right fa-fw"></i> $:_("No submission")</div>

            $if len([method for key, method in user_manager.get_auth_methods().items() if method.allow_share()]):
                <a id="share_my_submission" href="#" class="list-group-item list-group-item-action list-group-item-info $('hidden' if not eval_submission else '')" data-toggle='modal' data-target='#share'>
                    <i class="fa fa-share-alt fa-fw"></i>
                    $:_("Share my result")
                </a>
        </div>

        <h3>$:_("Submission history")</h3>
        <div id="submissions_restrictsize">
            <ul id="submissions" class="list-group">
                $if submissions:
                    $for submission in submissions:
                        <li class="submission list-group-item list-group-item-action
                            $if submission['status'] == 'done' and submission['result'] == 'success':
                                list-group-item-success
                            $elif submission['status'] == 'waiting':
                                list-group-item-warning
                            $else:
                                list-group-item-danger
                            "
                            data-submission-id="$submission['_id']">
                            $if task.get_accessible_time().is_open() or user_manager.has_admin_rights_on_course(course):
                                $if task.get_evaluate() == 'student' and students == submission['username']:
                                    <a class="allowed" title="Select for evaluation" data-toggle="tooltip" data-placement="right"><i class="fa fa-star fa-fw"></i></a>&nbsp;
                                $elif task.get_evaluate() == 'student':
                                    <a class="notallowed" title="Not the same group" data-toggle="tooltip" data-placement="right"><i class="fa fa-minus-circle fa-fw"></i></a>&nbsp;

                            <!-- Tags -->
                            $# This display a badge with the number of validated tags in each row of the submission history.
                            $# The badge is green (success style) if all tags are validated, blue (info style) otherwise.    
                            $if (len(visible_tags) > 0):
                                $ tags_ok_counter = 0
                                $ list_tags_ok = []
                                $for category in task_categories:
                                    $ tag = course_tags[category]
                                    $if tag.get_type() == 0 and (tag.is_visible_for_student() or user_manager.has_staff_rights_on_course(course)):
                                        $ class_tag = "badge alert-info"
                                        $if "tests" in submission and tag.get_id() in submission["tests"] and submission["tests"][tag.get_id()]:
                                            $ tags_ok_counter += 1
                                            $list_tags_ok.append(tag.get_name(user_manager.session_language()))
                                $if tags_ok_counter == len(visible_tags):
                                    <span class="badge alert-success" id="tag_counter">$tags_ok_counter</span>
                                $else:
                                    <span class="badge alert-info" id="tag_counter" data-toggle="tooltip" data-placement="left" title="$', '.join(list_tags_ok)">$tags_ok_counter</span>
                            <!-- End Tags -->
                        
                            $if "grade" in submission:
                                <span id="txt">$submission["submitted_on"].strftime("%d/%m/%Y %H:%M:%S") - $submission["grade"]%</span>
                            $else:
                                <span id="txt">$submission["submitted_on"].strftime("%d/%m/%Y %H:%M:%S")</span>
                        </li>
                        
                $else:
                    <li class="list-group-item list-group-item-action disabled submission-empty">$:_("No submission")</li>
            </ul>
        </div>
    $elif not user_manager.session_logged_in():
        $:include.signin_button()
    $elif course.is_registration_possible(user_info):
        <h3>$:_("Enroll in the course")</h3>

        <div class="alert alert-warning" role="alert">
            $:_("Please enroll in the course to be able to submit answers to problems.")
        </div>
        <div class="list-group">
            <a href="$get_homepath()/register/$course.get_id()" class="list-group-item list-group-item-action list-group-item-info">
                <i class="fa fa-sign-in fa-fw"></i>&nbsp; $:_("Enroll in the course")
            </a>
        </div>

$var Column: $:ColumnF()

$def NavbarF():
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            $if registered:
                <li class="breadcrumb-item"><a href="$get_homepath()/mycourses" title=$:_('"My courses"') data-toggle="tooltip" data-placement="bottom"><i class="fa fa-th-list"></i></a></li>
            $else:
                <li class="breadcrumb-item"><a href="$get_homepath()/courselist" title=$:_('"Course list"') data-toggle="tooltip" data-placement="bottom"><i class="fa fa-th-list"></i></a></li>
            <li class="breadcrumb-item"><a href="$get_homepath()/course/$task.get_course().get_id()">$course.get_name(user_manager.session_language())</a></li>
            <li class="breadcrumb-item active"><span>$task.get_name(user_manager.session_language()) <span class="sr-only">$:_("(current)")</span></span></li>
        </ol>
    </nav>
$var Navbar: $:NavbarF()

$# Start content
<h2>
    <div class="row">
    <div class="col-md-10">$task.get_name(user_manager.session_language())</div>
    <div class="col-md-2">
        $if not is_lti():
            <div class="pull-right">
                <div class="btn-group">
                    <button type="button" class="btn btn-info mr-1" data-toggle="collapse" data-target="#task_context">$:_("Collapse context")</button>
                    $if previous_taskid:
                        <a class="btn-sm btn btn-info" href="$get_homepath()/course/$course.get_id()/$previous_taskid" title=$:_('"Previous task"') data-toggle="tooltip" data-placement="bottom"><i class="fa fa-arrow-left"></i></a>
                    $if next_taskid:
                        <a class="btn-sm btn btn-info" href="$get_homepath()/course/$course.get_id()/$next_taskid" title=$:_('"Next task"') data-toggle="tooltip" data-placement="bottom"><i class="fa fa-arrow-right"></i></a>
                </div>
            </div>
    </div>
    </div>
</h2>
$# Input random
$# set up some useful variable that may be used by task author
$# variable "input" has to be accessible to the eventual javascript present in the context of the task.
<script>    
    var input = {
        "@lang": "$user_manager.session_language()",
        "@username": "$user_manager.session_username()",
        "@random": $input_random_list,
        "@state": "$(user_task.get('state', '') if registered else '')"
    }
</script>
<div id="task_context" class="collapse show">
    $:task.get_context(user_manager.session_language())
</div>
<hr/>
<div id="task_alert"></div>
<div id="ssh_template" style="display:none;">
    $if webterm_link:
        <div id="webterm">
            <input type="hidden" value="$webterm_link" id="webterm_link"/>
        </div>
        $:_("Alternatively, you can also paste this command into your terminal:") <br/>
    $else:
        $:_("Paste this command into your terminal:") <br/>

    <pre id="commandssh"></pre>
    $:_("The password to connect is {}").format("<code></code>")
</div>
<div id="messages" style="display:none;">
    <span id="answerall">$:_("Please answer to all the questions.")</span>
    <span id="internalerror">$:("Internal error")</span>
    <span id="invalidext">$:("{} has not a valid extension.")</span>
    <span id="filetooheavy">$:("{} is too heavy.")</span>
</div>

$if user_manager.has_admin_rights_on_course(course):
    <div class="modal fade" id="modal-debug">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">

                    <h4 class="modal-title">$:_("Debug information")</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body">
                    $:_("The raw data from the container will be displayed here, helping you to debug the task.<br/> This box is only displayed because you are an administrator of this course. It is not displayed to students.")
                    <hr/>
                    <div id="task_debug">

                    </div>
                </div>
            </div>
        </div>
    </div>

$if is_lti():
    $ action = "/lti/task"
$else:
    $ action = "/course/" + course.get_id() + "/" + task.get_id()

<form id="task" action="$(get_homepath() + action)" method="post" enctype="multipart/form-data"
    $for submission in submissions:
        $if submission["status"] == "waiting":
            data-wait-submission="$submission['_id']"
            $break
>
    $# Hide input random in form
    $ i = 0
    $for elem in input_random_list:
        <input type="hidden" name="@random_$i" id="random_input" value="$elem"/>
        $ i = i+1
    <input type="hidden" name="@action" value="submit"/>
    $for key, problem in enumerate(task.get_problems()):
        <div class="problem card card-default mb-4">
            $if len(task.get_problems()) != 1 or problem.get_name(user_manager.session_language()) != "":
                <div class="card-heading">
                    <h5 class="card-header">
                        $if len(task.get_problems()) != 1:
                            $:_("Question {}").format(str(key+1)):
                        $problem.get_name(user_manager.session_language())
                    </h5>

                </div>
            <div class="card-body">
                $:problem.show_input(template_helper, user_manager.session_language(), user_manager.session_username())
            </div>
        </div>

    $# no need to check with lti=True/False here as it was already checked by the calling python script.
    $ groups_ok = user_manager.task_can_user_submit(task, user_manager.session_username(), 'groups')
    $ tokens_ok = user_manager.task_can_user_submit(task, user_manager.session_username(), 'tokens')
    $if not registered:
        <button type="submit" class="btn btn-default btn-lg btn-block center-block" disabled="disabled">$:_("Please enroll in the course to submit.")</button>
    $elif groups_ok and tokens_ok:
        $if user_manager.has_admin_rights_on_course(course):
            <input type="hidden" name="@debug-mode" id="task-debug-mode" value=""/>
            <div class="row">
                <div class="col-xs-9 col-md-10">
                    <button type="submit" class="btn btn-default btn-lg btn-block center-block" id="task-submit">$:_("Submit")</button>
                </div>
                <div class="col-xs-3 col-md-2">
                    <button type="button" class="btn btn-info btn-lg btn-block center-block" id="task-submit-debug" data-toggle="tooltip"
                            data-placement="top" title=$:_('"Start remote SSH console with this input"')>
                        <i class="fa fa-terminal"></i>
                    </button>
                </div>
            </div>
        $else:
            <button type="submit" class="btn btn-default btn-lg btn-block center-block" id="task-submit">$:_("Submit")</button>
    $elif not task.get_accessible_time().is_open():
        <button type="submit" class="btn btn-default btn-lg btn-block center-block" disabled="disabled">$:_("The deadline is over, you cannot submit anymore")</button>
    $elif task.is_group_task() and not groups_ok:
        <button class="btn btn-default btn-lg btn-block center-block" disabled="disabled">$(_('Please register in a group'))</button>
    $elif not tokens_ok:
        <button type="submit" class="btn btn-default btn-lg btn-block center-block" disabled="disabled">
            $(_('You have reached the submission limit.') if not task.is_group_task() else _('Your group have reached the submission limit.'))
        $if task.get_submission_limit()["period"] > 0:
            <br/> $:_("It will be refilled within the next {} hour(s)").format(task.get_submission_limit()["period"])
        </button>
    $else:
        <button type="submit" class="btn btn-default btn-lg btn-block center-block" disabled="disabled">$:_("You are not allowed to submit")</button>
</form>

<!-- Modals -->
$ auth_methods = user_manager.get_auth_methods()

<div class="modal fade" id="share" tabindex="-1" role="dialog" aria-labelledby="socialModalLabel">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="socialModalLabel">$:_("Share my result on: ")</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
            <div class="modal-body">
                $for key, method in auth_methods.items():
                    $if method.allow_share():
                        <a href="#" onclick="share_submission('$method.get_id()')" class="btn btn-block btn-default">$method.get_name()</a>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
$ pdict = {problem.get_id(): problem.get_type() for problem in task.get_problems()}
var problems_types = $:pdict

$$(document).ready(function() {
    init_task_page("$task.get_evaluate()");
});

</script>

$# Input random
$# set up some useful variable that may be used by task author
<script>
    var input = {
        "@lang": "$user_manager.session_language()",
        "@username": "$user_manager.session_username()",
        "@random": $input_random_list
    }
</script>